<?php

function dnspod_log($msg, $flag = false) {
    $omsg = $msg;
    $msg = date('Y-m-d H:i:s') . '|' . $msg . PHP_EOL;
    if (defined('DNS_LOG_DIR')) {
        file_put_contents(DNS_LOG_DIR . '/dnspod.log', $msg, 8);
    }
    file_put_contents(dirname(__FILE__) . '/dnspod.log', $msg, 8);
    if ($flag) {
        file_put_contents(dirname(__FILE__) . '/notice.log', $msg, 8);
        if (defined('DNS_LOG_DIR')) {
            file_put_contents(DNS_LOG_DIR . '/notice.log', $msg, 8);
        }
    }
    echo $msg;
    if (substr($omsg, 0, strlen('WARNING:')) == 'WARNING:') {
        if (defined('DNS_LOG_DIR')) {
			file_put_contents(DNS_LOG_DIR . '/warning.log', $msg, 8);
		}
    }
}

function dnspod_call($api, $data) {
    $apiurl = 'https://dnsapi.cn/' . $api;
    $requestData = array(
        'login_email' => USER_EMAIL,
        'login_password' => USER_PASS,
        'format' => 'json',
        'lang' => 'cn',
        'error_on_empty' => 'no'
    );

    $requestData = array_merge($requestData, $data);

    dnspod_log('NOTICE: api[' . $api . '] request start,domain[' . $requestData['domain'] . '],domain_id[' . $requestData['domain_id'] . ']');

    $ch = @curl_init();
    if (!$ch) {
        exit('内部错误：服务器不支持CURL');
    }

    curl_setopt($ch, CURLOPT_URL, $apiurl);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($requestData));
    curl_setopt($ch, CURLOPT_USERAGENT, 'DNSPod API PHP Web Client/0.1');
    $result = curl_exec($ch);
    curl_close($ch);

    $arrResult = json_decode($result, true);
    if ($arrResult['status']['code'] != '1') {
        dnspod_log('WARNING: request status code is not 1, code[' . $arrResult['status']['code'] . '],json_encode[' . json_encode($arrResult) . ']');
        return false;
    }
    foreach ($arrResult as $key => $res) {
        if ($key != 'status') {
            dnspod_log('NOTICE: api[' . $api . '] post request success');
            return $arrResult;
        }
    }
    dnspod_log('WARNING: request no result,json_encode[' . json_encode($arrResult) . ']');
    return false;
}

function dnspod_add_domain_name($domain){
    $api = 'Domain.Create';
    $data = array(
        'domain' => $domain
    );
	$domainInfo = dnspod_call($api, $data);
    if ($domainInfo['status']['code'] == '1') {
        dnspod_log('域名添加成功,[' . $domain . ']', true);
		file_put_contents(DNS_LOG_DIR.'/addsuccess.log',$domain.PHP_EOL,8);
    }else{
		dnspod_log('添加域名失败,[' . $domain . '][' . json_encode($arrResult) . ']');
	}
    return $domainInfo;

}

#获取域名信息

function dnspod_get_domain_info($domain) {
    $api = 'Domain.Info';
    $data = array(
        'domain' => $domain
    );
    $domainInfo = dnspod_call($api, $data);
    $domain_id = $domainInfo['domain']['id'];
    if (!$domain_id || !is_numeric($domain_id)) {
        dnspod_log('WARNING: domain[' . $domain . '],get domain_id[' . $domain_id . '] error,json_encode[' . json_encode($domainInfo) . ']');
    }
    return $domainInfo['domain'];
}

#获取记录列表

function dnspod_get_domain_record_list($domain_id) {
    $api = 'Record.List';
    $data = array(
        'domain_id' => $domain_id,
    );
    $arrResult = dnspod_call($api, $data);
    if (empty($arrResult['records'])) {
        dnspod_log('WARNING: domain_id[' . $domain_id . '] get record list error,json_encode[' . json_encode($arrResult) . ']');
    }
	//print_r($arrResult['records']);die();
    return $arrResult['records'];
}

#添加A记录

function dnspod_add_domain_a_record($domain, $ip) {

    if (defined('DNS_LOG_DIR')) {
        $successRecordFile = DNS_LOG_DIR . '/success.json';
    } else {
        $successRecordFile = dirname(__FILE__) . '/success.json';
    }

    $jsonarray = json_decode(file_get_contents($successRecordFile), true);
	//print_r(file_get_contents($successRecordFile));die();
    if (!$jsonarray) {
        $jsonarray = array();
    }
    if (array_key_exists($domain, $jsonarray)) {
        dnspod_log('IP记录已经成功设置过,跳过,[' . $domain . ']=>[' . $ip . ']', true);
        return false;
    }


    $arrDomainInfo = explode('.', $domain);
    if (count($arrDomainInfo) != 3) {
        dnspod_log('WARNING: domain[' . $domain . '],format error');
    }
    $mainDomain = $arrDomainInfo[1] . '.' . $arrDomainInfo[2];
    $dnsDomainInfo = dnspod_get_domain_info($mainDomain);
    $domain_id = $dnsDomainInfo['id'];
    $subdomain = $arrDomainInfo[0];

    $arrRecordList = dnspod_get_domain_record_list($domain_id);
    foreach ($arrRecordList as $index => $record) {
        if ($record['name'] == $subdomain && 'A' == $record['type']) {
            dnspod_log('WARNING: 已经存在二级域名解析,domain[' . $domain . '] subdomain[' . $subdomain . '] exists');
            return false;
        }
    }

    $data = array(
        'domain_id' => $domain_id,
        'sub_domain' => $subdomain,
        'record_type' => 'A',
        'record_line' => '默认',
        'value' => $ip,
    );

    $api = 'Record.Create';
    $res = dnspod_call($api, $data);
    if ($res['status']['code'] == '1') {
        dnspod_log('添加A记录成功,[' . $domain . ']=>[' . $ip . ']', true);
        $jsonarray = json_decode(file_get_contents($successRecordFile), true);
        $jsonarray[$domain] = $ip;
        file_put_contents($successRecordFile, json_encode($jsonarray));
    }
    return $res;
}

//var_dump(dnspod_get_domain_record_list('10016591'));
//var_dump(dnspod_add_domain_a_record('*.cescheveux.com', '113.10.247.220'));
?>